import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList:[]

  },
  mutations: {
    repeat(state,playLoad){
      playLoad.count += 1
    },
    newOne(state,playLoad){
      playLoad.count = 1
      state.cartList.push(playLoad)
    },
    checkedChange(state,playLoad){
      state.cartList.forEach(item=>{
        if(item.iid === playLoad){
          item.isChecked = !item.isChecked
        }
      })

    },
    selectAll(state){
      state.cartList.forEach(item=>{
         item.isChecked = true
      })
    },
    emptyAll(state){
      state.cartList.forEach(item=>{
         item.isChecked = false
      })
    }
  },
  actions: {

      addCart(context,playLoad){
        return new Promise((resolve,reject)=>{
          // 判断playLoad是否已经存在
          const oldItem = context.state.cartList.find(item=>{
            return item.iid == playLoad.iid
          })
          if(oldItem!==undefined){
            context.commit('repeat',oldItem)
            resolve('商品+1')
          }else{
            context.commit('newOne',playLoad)
            resolve('商品添加')
          }
        })
      },
      selectAll(context,playLoad){      
          if(playLoad){
            context.commit('selectAll')
          }else{
            context.commit('emptyAll')
           
          }
      }

  },
  getters:{
    cartLength(state){
      return state.cartList.length
    },
    cartList(state){
      return state.cartList
    },
    totapPrice(state){
      let total=0;
      state.cartList.forEach(item=>{
        if(item.isChecked){
           total+= parseInt(item.price) * parseInt(item.count)
        }
      })
      return total.toFixed(2)
    },
    isSelected(state){
      return !state.cartList.find((item)=>{return item.isChecked !== true})
    }
  }
})
